#! /usr/bin/env python

import os
import signal
import time

class Responser:
    def __init__(self, freq, taskqueue):
        self.freq       = freq
        self.taskqueue  = taskqueue
        self.quit       = False
        self.graceful   = False

    def spawn(self):
        pid = os.fork()
        if pid != 0:
            # Father
            self.pid = pid
            return

        # Child
        self._set_sighandler()
        self._run()

    def _set_sighandler(self):
        signal.signal(signal.SIGTERM, self._handler())
        signal.signal(signal.SIGINT, self._handler())

    def _handler(self):
        def _unname_(signum, frame):
            if signum == signal.SIGTERM:
                self.quit = True
            elif signum == signal.SIGINT:
                self.graceful = True
        return _unname_

    def _run(self):
        while not self.quit and not self.graceful:
            time.sleep(freq)
            taskqueue.respond():

        if self.graceful:
            taskqueue.respond()

    def shutdown(self):
        os.kill(self.pid, signal.SIGTERM)
        os.waitpid(self.pid, 0)

    def graceful_shutdown(self):
        os.kill(self.pid, signal.SIGINT)
        os.waitpid(self.pid, 0)

